<template>
  <div class="input">
    <label class="label">
      <i class="icon iconfont" :class="icon" v-show="icon.length"></i>
      <input :class="{'indent':icon.length}"
             :placeholder="placeholder"
             type="text" v-model="text" @blur="onBlur"/>
    </label>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';

export default defineComponent({
  name: 's-input',
  emits: ['update:value', 'change'],
  props: {
    icon: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    value: {
      required: true,
      type: [String, Number],
      default: '',
    },
  },
  setup(props, { emit }) {
    function transformType(val: string | number) {
      const isString = typeof props.value === 'string';
      if (isString) {
        return val.toString();
      } else {
        return parseFloat(val.toString());
      }

    }

    const text = ref(props.value);

    watch(() => props.value, (val) => {
      text.value = val;
    });
    return {
      text,
      onBlur() {
        const v = transformType(text.value);
        emit('update:value', v);
        emit('change', v);
      },
    };
  },
});
</script>
<style scoped lang="scss">
.input {
  position: relative;

  .label {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-content: center;

    .icon {
      position: relative;
      left: 22px;
      top: 3px;
    }

    input {
      box-sizing: border-box;
      width: 100%;
    }

    .indent {
      padding-left: 24px;
    }
  }

}
</style>
